# -*- coding: utf-8 -*-
"""
Created on Tue Feb  6 17:53:30 2018

@author: Administrator
"""
import re
import urllib.request    
from HandleJs import Py4Js  
import pyperclip   
    
def open_url(url):    
    headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0'}      
    req = urllib.request.Request(url = url,headers=headers)    
    response = urllib.request.urlopen(req)    
    data = response.read().decode('utf-8')    
    return data    
    
def translate(content):  
    js = Py4Js()  
    tk = js.getTk(content)  
  
    content = urllib.parse.quote(content)  
    url = "http://translate.google.cn/translate_a/single?client=t"\
    "&sl=EN&tl=zh-CN&hl=EN&dt=at&dt=bd&dt=ex&dt=ld&dt=md&dt=qca"\
    "&dt=rw&dt=rm&dt=ss&dt=t&ie=UTF-8&oe=UTF-8&clearbtn=1&otf=1&pc=1"\
    "&srcrom=0&ssel=0&tsel=0&kc=2&tk=%s&q=%s" % (tk, content)  
  
    result = open_url(url)  
    end = result.find("\",")   
    texts = result[4:end]  
    return texts  
  
  
if __name__ == "__main__":  
    copyBuff=''  
    while 1:
        results=''
        copyedText=pyperclip.paste()
        if copyBuff!=copyedText:
            copyBuff=copyedText
            content = copyBuff.replace('\n', ' ').replace('\r',' ')
            if content == 'q!':    
                break
            texts=re.split(('[,.?!]'),content)    
            for i in range(len(texts)): 
                results = str(results)+","+str(translate(str(texts[i])))  
            print (results)            